#include "i2c.h"
#include "c51.h"

#define SCL P2_1
#define SDA P2_0

void i2c_start(void) {
  SDA = 1;
  SCL = 1;
  SDA = 0;
  SCL = 0;
}

void i2c_stop(void) {
  SDA = 0;
  SCL = 1;
  SDA = 1;
}

void i2c_write(u8 byte) {
  for (u8 i = 0; i < 8; ++i) {
    SDA = byte & (0b10000000 >> i);
    SCL = 1;
    SCL = 0;
  }
}

u8 i2c_read(void) {
  u8 byte = 0;
  SDA = 1;
  for (u8 i = 0; i < 8; ++i) {
    SCL = 1;
    if (SDA) {
      byte |= 0b10000000 >> i;
    }
    SCL = 0;
  }
  return byte;
}

void i2c_write_ack(_Bool bit) {
  SDA = bit;
  SCL = 1;
  SCL = 0;
}

Bit i2c_read_ack(void) {
  Bit bit;
  SDA = 1;
  SCL = 1;
  bit = SDA;
  SCL = 0;
  return bit;
}
